/*
 * @lc app=leetcode.cn id=108 lang=cpp
 *
 * [108] 将有序数组转换为二叉搜索树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
private:
    TreeNode *traversal(vector<int> &nums, int left, int right)
    {
        //实际上是分割区间 找出中心点 然后分割
        //区间 左闭右开
        //先序遍历构造节点
        if (left >= right)
        {
            return NULL;
        }
        //因为左闭右开区间 所以区间大小为偶数的时候 mid取靠右边的数
        int mid = left + (right - left) / 2; //避免溢出

        TreeNode *node = new TreeNode(nums[mid]);
        node->left = traversal(nums, left, mid);
        node->right = traversal(nums, mid + 1, right);
        return node;
    }

public:
    TreeNode *sortedArrayToBST(vector<int> &nums)
    {
        //从有序数组生成二叉平衡搜索树
        TreeNode *root = traversal(nums, 0, nums.size());
        return root;
    }
};
// @lc code=end
